﻿using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsWeChartDemo.Common;
using WindowsFormsWeChartDemo.Models;

namespace WindowsFormsWeChartDemo
{
    public partial class MainWinForm : Form
    {
        private WeChartHelper chartHelper = new WeChartHelper();
        private Logger logger = LogManager.GetCurrentClassLogger();
        public MainWinForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void MainWinForm_Load(object sender, EventArgs e)
        {
            chartHelper.AddToQueueEvent += AddToQueueEvent;
            SendMessageJob.WriteLogEvent += Write;
            //启动定时任务
            ReportJobScheduler.Start();
        }
        private void MainWinForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //停止定时任务
            ReportJobScheduler.Shutdown();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SendMessageModel model = new SendMessageModel
            {
                appid = tb_appid.Text,
                appsecret = tb_appsecret.Text,
                openid = tb_openid.Text,
                template_id = tb_template_id.Text,
                message = tb_message.Text
            };
            chartHelper.AddMessage(model);
        }

        private void AddToQueueEvent(SendMessageModel model)
        {
            string msg = $"添加到队列完成：AppID：{model.appid},OpenId:{model.openid},Message:{model.message}";
            logger.Info(msg);
            Write(msg);
        }

        private void Write(string log)
        {
            this.lv_log.BeginUpdate();
            bool scroll = false;
            if (this.lv_log.TopIndex == this.lv_log.Items.Count - (int)(this.lv_log.Height / this.lv_log.ItemHeight))
                scroll = true;
            this.lv_log.Items.Add(log);
            if (scroll)
                this.lv_log.TopIndex = this.lv_log.Items.Count - (int)(this.lv_log.Height / this.lv_log.ItemHeight);
            this.lv_log.EndUpdate();
        }
    }
}
